﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Windows.Forms;

using NAudio.CoreAudioApi;

namespace MultiVolumeControl.Core
{
	public static class MiscUtils {
		
		public static string AsHex(byte bit)
		{
			return AsHex(new [] { bit });
		}
		
		public static string AsHex(byte[] bytes)
		{
			return (new SoapHexBinary(bytes)).ToString();
		}
		
		public static IDictionary<int,object> GetProperties(this MMDevice device)
		{
			var dict=new Dictionary<int,object>();
			for(int i=0;i<device.Properties.Count;i++){
				try{
					dict[device.Properties.Get(i).propertyId]=device.Properties.GetValue(i).Value;
				}catch(NotImplementedException){
				}
			}
			return dict;
		}
		
		public static IDictionary<string,AudioWrapper> GetDeviceMap()
		{
			var devices = new Dictionary<string,AudioWrapper>();
			var enumerator = new MMDeviceEnumerator();
			foreach(var device in enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)){
				var name = device.FriendlyName+" ("+device.DeviceFriendlyName+")";
				var id = '{' + device.ID.Split(new [] { "}.{" }, StringSplitOptions.None)[1];
				devices[name] = new AudioWrapper(device.AudioEndpointVolume,id);
			}
			return devices;
		}
		
		public static Tuple<ModifierKeys,Keys> ParseHotKey(NameValueCollection config, string name)
		{
			ModifierKeys mod;
			Keys key;
			return ModifierKeys.TryParse(config[name+"_mod"], true, out mod)
				&& Keys.TryParse(config[name+"_key"], true, out key)
				? Tuple.Create(mod,key) : null;
		}
		
		public static string AsString(Tuple<ModifierKeys, Keys> tuple)
		{
			return tuple == null ? string.Empty : " ("+tuple.Item1.ToString().Replace(',',' ')+" "+tuple.Item2+")";
		}
	}
}